package com.top.mall.main.goods

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeFragment
import com.top.mall.R
import com.top.mall.entity.*
import com.top.mall.jetpack.vm.GoodsViewModel
import com.top.mall.main.goods.adapter.GoodsLabelAdapter
import com.top.mall.main.goods.adapter.GoodsCategoryAdapter
import com.top.mall.popup.GoodsScreenPopup
import kotlinx.android.synthetic.main.fragment_goods_category.*
import kotlinx.android.synthetic.main.include_goods_screen.*

class GoodsCategoryFragment : OwnerViewModeFragment<GoodsViewModel>() {

    private var twoCateList: CateList? = null

    private val goodsSearchAdapter: GoodsCategoryAdapter =
        GoodsCategoryAdapter(GoodsCategoryAdapter.Type.CATEGORY)

    private val goodsLabelAdapter: GoodsLabelAdapter =
        GoodsLabelAdapter()

    private var goodsRequest: GoodsRequest = GoodsRequest()

    private val goodsScreenPopup: GoodsScreenPopup by lazy {
        GoodsScreenPopup(requireContext()) { serviceId ->
            fillGoodsListSort(goodsRequest.apply { service_id = serviceId })
        }
    }

    companion object {
        private const val EXTRA_NAME_CATE = "EXTRA_NAME_CATE"
        fun newInstance(cateList: CateList): GoodsCategoryFragment {
            val bundle: Bundle = Bundle().apply {
                putParcelable(EXTRA_NAME_CATE, cateList)
            }
            return GoodsCategoryFragment().apply {
                arguments = bundle
            }
        }
    }

    override val layoutResId: Int
        get() = R.layout.fragment_goods_category

    override fun viewModel(): GoodsViewModel {
        return createViewModel()
    }

    override fun initView() {

        //获取传值
        twoCateList = arguments?.getParcelable(EXTRA_NAME_CATE)

        twoCateList?.let {
            goodsRequest.apply { cat_id = it.id }
        }

        //初始三级分类标签适配器
        rvGoodsCateLabel.apply {
            layoutManager = LinearLayoutManager(requireContext()).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
        }.adapter = goodsLabelAdapter.apply {
            twoCateList?.let {
                val data = CateList(
                    goods_cat = it.goods_cat,
                    id = it.id,
                    image = it.image,
                    label_color = it.label_color,
                    label_text = it.label_text,
                    level = it.level,
                    name = "全部"
                )
                if (it.goods_cat == 0) {
                    setNewInstance(mutableListOf(data))
                }
            }
        }

        goodsLabelAdapter.setOnItemClickListener { _, _, position ->
            val itemData: CateList = goodsLabelAdapter.getItem(position)
            goodsLabelAdapter.selectedPosition = position
            viewModel.goodsList(goodsRequest.apply { cat_id = itemData.id })
        }

        //初始物品适配器
        rvGoodsCateBody.apply {
            itemAnimator?.changeDuration = 0
        }.adapter = goodsSearchAdapter.apply {
            setEmptyView(createLoadingView())
        }
        goodsSearchAdapter.setOnItemChildClickListener { adapter, view, position ->
            val itemData: GoodsList = goodsSearchAdapter.getItem(position)
            when (view.id) {
                R.id.flCategoryBodyPlus -> {
                    val num: Int = itemData.cart_num + 1
                    if (itemData.cart_id == 0 || itemData.cart_num == 0) {
                        viewModel.cartAdd(itemData.id, num, position)
                    } else {
                        viewModel.cartChangeNum(itemData.cart_id, num, position, true)
                    }
                }
                R.id.flCategoryBodyReduce -> {
                    val num: Int = itemData.cart_num - 1
                    if (num == 0) {
                        viewModel.cartDelete(arrayOf(itemData.cart_id), CartType.DELETE, position)
                    } else {
                        viewModel.cartChangeNum(itemData.cart_id, num, position, true)
                    }
                }
            }
        }

        //筛选
        llGoodsScreenScreen.setOnClickListener {
            viewModel.goodsService()
        }
        //价格排序
        llGoodsScreenSortPrice.setOnClickListener {
            fillGoodsListSort(goodsRequest.apply {
                sort = "price"
                sort_asc = when (sort_asc) {
                    null -> "asc"
                    "asc" -> "desc"
                    else -> null
                }
                count = null
            })
        }
        //有货
        llGoodsScreenSortCount.setOnClickListener {
            fillGoodsListSort(goodsRequest.apply {
                sort = null
                sort_asc = null
                count = if (count == 1) null else 1
            })
        }
    }

    override fun initData() {

        twoCateList?.let {
            viewModel.goodsList(goodsRequest)
            if (it.goods_cat == 0) {
                viewModel.categoryList(it.id, level = 3)
            }
        }
    }

    fun cartListRestart() {
        twoCateList?.let {
            if (goodsSearchAdapter.data.size == 0)
                return@let
            viewModel.goodsList(goodsRequest)
        }
    }

    override fun initViewMode() {

        //监听三级分类数据
        viewModel.cateListLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            if (response.data?.level != 3)
                return@Observer
            response.data?.data?.let {
                goodsLabelAdapter.addData(it)
            }
        })

        //监听物品列表数据
        viewModel.goodsListLiveData.observe(viewLifecycleOwner, Observer { response ->

            when (response.status) {
                Status.START -> {
                    goodsSearchAdapter.setEmptyView(createLoadingView())
                }
                Status.SUCCESS -> {
                    response.data?.data?.let {
                        if (it.size == 0) {
                            goodsSearchAdapter.setEmptyView(createNullDataView())
                        }
                        goodsSearchAdapter.setNewInstance(it)
                    }
                }
                Status.FAILURE -> {
                    goodsSearchAdapter.setEmptyView(createLoadingView())
                }
            }
        })

        //监听购物车添加
        viewModel.cartAddLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.let {
                goodsSearchAdapter.setData(it.position, it.goods_num, it.cart_id)
            }
        })

        //监听购物车加减
        viewModel.cartChangeNumLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.let {
                goodsSearchAdapter.setData(it.position, it.goods_num)
            }
        })

        //监听购物车删除
        viewModel.cartDeleteLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.let {
                goodsSearchAdapter.setData(it.position, 0)
            }
        })

        //监听商品标签数据
        viewModel.goodsLabelLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                Status.START -> {
                    goodsScreenPopup.showPopupWindow(includeGoodsCateSort)
                }
                Status.SUCCESS -> response.data?.data?.let {
                    goodsScreenPopup.fillData(it, includeGoodsCateSort)
                }
                Status.FAILURE -> {
                    toast(response.error?.msg)
                }
            }
        })

    }


    private fun fillGoodsListSort(goodsRequest: GoodsRequest) {

        tvGoodsScreenScreen.setTextColor(
            requireActivity().resources.getColor(
                if (goodsRequest.service_id == null) R.color.FF_333333 else R.color.colorMain
            )
        )
        ivGoodsScreenScreen.setColorFilter(
            requireActivity().resources.getColor(
                if (goodsRequest.service_id == null) R.color.FF_CCCCCC else R.color.colorMain
            )
        )

        tvGoodsScreenSortPrice.setTextColor(
            requireActivity().resources.getColor(
                if (goodsRequest.sort_asc == null) R.color.FF_333333 else R.color.colorMain
            )
        )
        ivGoodsScreenSortPrice.setImageResource(
            when (goodsRequest.sort_asc) {
                "asc" -> R.drawable.ic_sort_price_1
                "desc" -> R.drawable.ic_sort_price_2
                else -> R.drawable.ic_sort_price_0
            }
        )

        tvGoodsScreenSortCount.setTextColor(
            requireActivity().resources.getColor(
                if (goodsRequest.count == 1) R.color.colorMain else R.color.FF_333333
            )
        )
        ivGoodsScreenSortCount.setColorFilter(
            requireActivity().resources.getColor(
                if (goodsRequest.count == 1) R.color.colorMain else R.color.FF_CCCCCC
            )
        )

        viewModel.goodsList(goodsRequest)
    }

    private fun createLoadingView(): View {
        return layoutInflater.inflate(R.layout.dialog_load_style_2, null)
    }

    private fun createNullDataView(): View {
        return layoutInflater.inflate(R.layout.view_empty_null, null)
    }

}